import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElNotification } from 'element-plus';
import router from "@/router/index.js"
import { jwtDecode } from 'jwt-decode';
axios.create({
  // baseURL: 'http://127.0.0.1:8080',
  timeout: 5 * 1000,
  withCredentials: true,
});

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';

axios.interceptors.request.use(
  (config: AxiosRequestConfig | any) => {
    const access_token = localStorage.getItem("access_token");
    if (!access_token) {
      if (location.hash != '#/login') {
        router.replace('/login');
      }
    } else {
      try {
        const decoded = jwtDecode(access_token);
      } catch (error) {
        console.log("解析token出错:::::", error);
      }
      config.headers["authorization"] = "Bearer " + access_token;
    }
    if (process.env.NODE_ENV == 'development') {
      config.headers['x-simulated-trading'] = 1;
      config.headers['X-Locale'] = 'zh_CN';
    }
    return config;
  },
  (error: any) => {
    ElMessage.closeAll();
    ElNotification.error('请求错误！');
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response: AxiosResponse) => {
    const testOkx = /\/okxHost\//g;
    const testOkxApi = /\/okx-api\//g;
    const testBitget = /\/bitget-api\//g;
    const testBitgetHost = /\/bitgetHost\//g;
    const testHuobiHost = /\/huobiHost\//g;
    // console.log("response:::", response);
    switch (response?.status) {
      case 200: {
        if (testOkx.test(response.config.url)) {
          return response.data.data;
        } else if (testBitget.test(response.config.url) || testBitgetHost.test(response.config.url)) {
          return response.data.data;
        } else if (testHuobiHost.test(response.config.url)) {
          if (response.data.code != 200 || response.data.ok != true) {
            ElMessage.error(response.data?.message);
          }
          return response?.data ? response.data : response;
        } else {
          return response?.data ? response.data : response;
        }
      }
      case 201: {
        if (testHuobiHost.test(response.config.url)) {
          if (response.data.code != 200 || response.data.ok != true) {
            ElMessage.error(response.data?.message);
          }
          return response?.data ? response.data : response;
        }
      }
      case 210: {
        if (testBitget.test(response.config.url) || testBitgetHost.test(response.config.url)) {
          const _code = response.data.code;
          if (_code == "00000") {
            return response.data.data;
          } else {
            ElMessage.warning(response.data.msg);
            return Promise.reject(response.data.msg);
          }
        } else {
          return response?.data;
        }
      }
      case 401: {
        ElMessage.warning('请先登录');
        router.push('/login');
        break;
      }
      case 403: {
        ElMessage.warning('拒绝访问');
        break;
      }
      case 222: {//自定义服务端错误
        ElMessage.error(response.data.message);
        Promise.reject(response.data.message);
        break;
      }
      default: {
        return response;
      }
    }
    // return response?.data;
  },
  (error: any) => {
    ElMessage.closeAll();
    console.log("axios error::::", error, error?.status, error?.response, error?.message);
    const { response } = error;
    if (response?.status == 401) {
      localStorage.removeItem("access_token");
      ElMessage.warning('请重新登录');
      router.push('/login');
      return Promise.reject(error);
    } else if (response?.status == 406) {
      localStorage.removeItem("access_token");
      ElMessage.error(response.data.message);
      return Promise.reject(error);
    } else if (response?.status == 500) {
      ElMessage.error(error?.message ?? '服务器错误！');
      return Promise.reject(error);
    } else if (response?.status == 404) {
      ElMessage.error('请求路径不存在');
      return Promise.reject(error);
    } else if (error?.message == `Cannot read properties of undefined (reading 'cancelToken')`) {
      return Promise.resolve();
    } else if (response?.status == 555) {
      const _msg = error?.response.data.message?.msg ?? error?.response.data.message;
      if (_msg == 'Maximum number of access attempts exceeded.') {
        ElMessage.error("服务器繁忙请重试");
      } else {
        ElMessage.error(_msg ?? '未知逻辑错误');
      };
      return Promise.reject(_msg);
    } else {
      ElMessage.error('响应错误！');
      return Promise.reject(error);
    }
  }
);

export default axios;
